package com.qingcheng.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.Spu;
import com.qingcheng.service.goods.SpuService;
import com.qingcheng.util.RestHighLevelClientFactory;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MessageConsumer3 implements MessageListener {
    @Value("${host}")
    private String host;
    @Value("${port}")
    private int port;
    @Reference
    private SpuService spuService;

    @Override
    public void onMessage(Message message) {
        //获取到spuid
        String spuid = new String(message.getBody());
        RestHighLevelClient restHighLevelClient = RestHighLevelClientFactory.getRestHighLevelClient(host, port);
        Goods goods = spuService.findGoodsById(spuid);
        List<Sku> skuList = goods.getSkuList();
        Spu spu = goods.getSpu();
        try {
            for (Sku sku : skuList) {
                IndexRequest indexRequest = new IndexRequest("sku", "doc", sku.getId());
                Map skuMap = new HashMap();
                skuMap.put("name", sku.getName());
                skuMap.put("brandName", sku.getBrandName());
                skuMap.put("categoryName", sku.getCategoryName());
                skuMap.put("price", sku.getPrice());
                skuMap.put("createTime", sku.getCreateTime());
                skuMap.put("saleNum", spu.getSaleNum());
                skuMap.put("commentNum", spu.getCommentNum());
                Map specMap = new HashMap();
                String spec = sku.getSpec();
                Map<String, String> map = JSON.parseObject(spec, Map.class);
                for (String key : map.keySet()) {
                    specMap.put(key, map.get(key));
                }
                skuMap.put("spec", specMap);
                indexRequest.source(skuMap);
                IndexResponse response = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
                int status = response.status().getStatus();
                System.out.println(status);
            }
            restHighLevelClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
